<?php
/**
 * 
 * @authors Liujinbi (857053791@QQ.com)
 * @date    2017-08-03 15:11:12
 * @version $Id$
 */

namespace app\agent\controller;

use think\Request;
use think\Db;
use think\Session;
use think\Config;

class Cart extends Shopbase
{	
	/**
	 * 购物车数据
	 * @return [type] [description]
	 */
	public function index(){
		$uid = $this->shop_uid;

		$list = Db::field('g.*,sval.*,c.*')
		->table('sdzx_goods')->alias('g')
		->join('sdzx_goods_specval sval','g.goods_id=sval.goods_id')
		->join('sdzx_user_cart c','sval.specval_id=c.specval_id and sval.goods_id=c.goods_id')
		->where("c.user_id={$uid} and c.addbyagent>0")
		->select();
		$data['list'] = $list;
		return $this->fetch('',$data);
	}

	/**
	 * 购物车数量
	 * @return [type] [description]
	 */
	public function cartNum()
	{
		$uid = $this->shop_uid;
		$num = Db::field('sum(num) as num')->name('user_cart')->where("user_id={$uid} and addbyagent>0")->find();
		$this->success('success','',$num['num']);
	}

	/**
	 * 添加商品
	 */
	public function edit()
	{
		$uid = $this->shop_uid;
		$goods_id = Request()->param('goods_id','');
		$specval_id = Request()->param('specval_id','');
		$num = Request()->param('num');
		if (empty($goods_id) || empty($specval_id) || empty($uid)) {
			$this->error('缺少参数');
		}

		//检查商品是否存在
		$issetgoods = Db::name('goods_specval')->where(['goods_id'=>$goods_id,'specval_id'=>$specval_id])->find();
		!$issetgoods && $this->error('商品不存在');

		//检查购物车是否存在该商品
		$incart = Db::name('user_cart')->where(['goods_id'=>$goods_id,'specval_id'=>$specval_id,'user_id'=>$uid,'addbyagent'=>['neq',0]])->find();

		$id = 0;
		if ($incart) {
			if($num){
				$re = Db::name('user_cart')->where(['cart_id'=>$incart['cart_id']])->update(['num'=>$num]);
			}else{
				$re = Db::name('user_cart')->where(['cart_id'=>$incart['cart_id']])->setInc('num',1);
			}
			if ($re!==false) {
				$id = $incart['cart_id'];
			}
		}else{
			$data = [
				'user_id'    => $uid,
				'goods_id'   => $goods_id,
				'specval_id' => $specval_id,
				'add_time'   => date("Y-m-d h:i:s"),
				'shop_id'    => $this->shop_id,
				'num'        => $num?:1,
				'addbyagent' => $this->uid
			];
			$id = Db::name('user_cart')->insertGetId($data);
		}
		if ($id) {
			$this->success('添加成功','');
		}else{
			$this->error('添加失败');
		}
	}

	/**
	 * 删除
	 * @return [type] [description]
	 */
	public function del()
	{
		$cart_id = Request()->param('cart_id');

		empty($cart_id) && $this->error('缺少参数');
		$re = Db::name('user_cart')->where(['cart_id'=>['in',$cart_id]])->delete();
		if ($re) {
			$this->success('操作成功','');
		}else{
			$this->error('操作失败');
		}
	}

	public function payPage()
	{
		$param = Request()->param();
		!$param['param'] && $this->error('未选择商品');
		$data = json_decode($param['param'],true);

		//查出商品
		$goods = []; $totalprice=0; $sval_arr=[];
		foreach ($data as $k => $v) {
			$tmp = Db::connect([],'goods')->table('sdzx_goods')->alias('g')
			->join('sdzx_goods_specval sval','g.goods_id=sval.goods_id')
			->where("sval.specval_id={$v['specval_id']}")
			->find();
			$tmp['num'] = $v['num'];
			$tmp['sval_price'] = $tmp['price'] * $v['num'];
			$totalprice += $tmp['sval_price'];
			$sval_arr[]= $v['specval_id'].'_'.$v['num'];
			$goods[] = $tmp;
		}
		$data['goods'] = $goods;
		$data['totalprice'] = $totalprice;
		$data['sval_str'] = implode(',',$sval_arr);

		//配送费 配送时间
		$data['delivery_fee'] = $this->shippingMoney($data['totalprice']);
        if (Config::get('sites.scheduling')) {
            $data['shippingmsg'] = Config::get('sites.scheduling').'前下单当日配送，'.Config::get('sites.scheduling').'后下单将次日配送';
        } else {
            $data['shippingmsg'] = "预计配送时间".date('m月d日').' 7:00-11:00';
        }

        //收获地址
        $data['address'] = Db::name('user_address')->where(['user_id'=>$this->shop_uid])->order('type desc')->find();


		return $this->fetch('',$data);
	}

	/**
    * 获取用户订单运费  之后可能跟用户等级有关
    * @return [type] [description]
    */
    public function shippingMoney($order_money=0)
    {
        $uid = $this->shop_uid;
        $free_shipping = Db::field('ul.free_shipping')
        ->table('sdzx_shop')->alias('s')
        ->join('sdzx_user_level ul','s.level=ul.level_id','left')
        ->where("s.user_id={$uid}")
        ->value('free_shipping');

        $return_arr = [
            'delivery_fee' => Config::get('sites.delivery_fee')?:0,
            'free_delivery_fee' => Config::get('sites.free_delivery_fee')?:0
        ];

        if ($free_shipping) {
            $return_arr['delivery_fee'] = 0;
        }else if ($order_money>0 && $return_arr['free_delivery_fee']>0 && $order_money>=$return_arr['free_delivery_fee']) {
            $return_arr['delivery_fee'] = 0;
        }
        
        return $return_arr;
    }

    /**
     * 订单提交页面相关数据
     * @return [type] [description]
     */
    public function orderOther()
    {
        $data['delivery_fee'] = $this->shippingMoney();
        if (Config::get('sites.scheduling')) {
            $data['shippingmsg'] = Config::get('sites.scheduling').'前下单当日配送，'.Config::get('sites.scheduling').'后下单将次日配送';
        } else {
            $data['shippingmsg'] = "预计配送时间".date('m月d日').' 7:00-11:00';
        }
        $this->success('success', '', $data);
    }

    /**
     * 用户地址
     * @param string $value [description]
     */
    public function address()
    {
    	$list = Db::name('user_address')->where(['user_id'=>$this->shop_uid])->order('type desc')->select();
    	return $this->fetch('',['list'=>$list,'shop_uid'=>$this->shop_uid]);
    }

    /**
     * 添加用户地址
     * @param string $value [description]
     */
    public function addAddress()
    {
    	$param = request()->param();
    	!$param['pcd'] && $this->error('参数错误');
    	!$param['address'] && $this->error('参数错误');
    	!$param['name'] && $this->error('参数错误');
    	!$param['phone'] && $this->error('参数错误');

    	$data = [
    		'user_id' => $this->shop_uid,
    		'pcd' => $param['pcd'],
    		'address' => $param['address'],
    		'name' => $param['name'],
    		'phone' => $param['phone'],
    	];
    	$re = Db::name('user_address')->insert($data);
    	if ($re) {
    		$this->success('保存成功','refresh');
    	}else{
    		$this->error('保存失败');
    	}
    }
}